<template>
  <div class="app-container">
    <div class="edit-button">
      <el-button type="primary"
                 plain
                 @click="createFood">新建餐品</el-button>
    </div>
    <el-table v-loading="listLoading"
              :data="list"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row>
      <el-table-column align="center"
                       label="编号"
                       width="170">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="餐品名称"
                       width="170"
                       align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="餐品图片"
                       width="170"
                       align="center">
        <template slot-scope="scope">
          <div class="demo-image">
            <el-image style="width: 50px; height: 50px"
                      :src="scope.row.img_list"
                      fit="cover"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="描述">
        <template slot-scope="scope">
          <span>{{ scope.row.desc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格"
                       width="170"
                       align="center">
        <template slot-scope="scope">
          ￥ {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col"
                       label="状态"
                       width="170"
                       align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.state | statusFilter">{{ getStatus(scope.row.state) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       prop="created_at"
                       label="操作"
                       width="200">
        <template slot-scope="scope">
          <el-button type="primary"
                     icon="el-icon-edit"
                     circle
                     @click="editFood(scope.row)"></el-button>
          <el-button type="danger"
                     icon="el-icon-delete"
                     circle
                     @click="deleteFood(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Form -->
    <el-dialog title="餐品详细信息"
               :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="餐品名称"
                      :label-width="formLabelWidth">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="餐品描述"
                      :label-width="formLabelWidth">
          <el-input v-model="form.desc"></el-input>
        </el-form-item>
        <el-form-item label="餐品图片"
                      :label-width="formLabelWidth">
          <el-upload class="upload-demo"
                     action="http://localhost:9000/file/upload"
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     :file-list="fileList"
                     :on-exceed="handleExceed"
                     :on-success="uploadSuccess"
                     list-type="picture"
                     multiple
                     :limit="1"
                     :before-upload="beforeAvatarUpload">
            <el-button size="small"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格"
                      :label-width="formLabelWidth">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="状态"
                      :label-width="formLabelWidth">
          <el-select v-model="form.state"
                     placeholder="请选择餐品状态">
            <el-option v-for="item in options"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary"
                   @click="submit">提 交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { GetFoodList, CreateFood, UpdateFood, DeleteFood } from '@/api/food'

export default {
  filters: {
    statusFilter (state) {
      const statusMap = {
        "1": 'success',
        "2": 'danger'
      }
      return statusMap[state]
    }
  },
  data () {
    return {
      list: null,
      listLoading: true,
      dialogFormVisible: false,
      form: {
        restaurant_id: 1,
        name: '',
        desc: '',
        price: 0,
        img_list: '',
      },
      formLabelWidth: '80px',
      fileList: [],
      operation: 0, // 0-新建 1-更新
      options: [{
        value: 1,
        label: '正常'
      }, {
        value: 2,
        label: '售罄'
      }],
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      var that = this;
      GetFoodList({
        rest_id: 1
      }
      ).then(res => {
        that.list = res.data
      }).catch(err => {
        console.log(err)
      })
      this.listLoading = false
    },
    editFood (row) {
      this.dialogFormVisible = true
      this.form = row
      this.operation = 1;
      this.fileList = [{
        name: this.form.name,
        url: this.form.img_list,
      }]
    },
    deleteFood (id) {
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteFood(id).then(res => {
          console.log(res);
        }).catch(err => {
          console.log(err);
        })
        location.reload();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submit () {
      if (this.operation === 0) {
        CreateFood(this.form).then(res => {
          console.log(res);
          this.form = {};
        }).catch(err => {
          console.log(err);
        })
      } else {
        UpdateFood(this.form).then(res => {
          console.log(res);
          this.form = {};
        }).catch(err => {
          console.log(err);
        })
      }
      this.dialogFormVisible = false;
    },
    uploadSuccess (response, file, fileList) {
      this.form.img_list = response.data.url;
    },
    createFood (row, event, column) {
      this.dialogFormVisible = true
      this.operation = 0;
    },
    getStatus (state) {
      return state === 2 ? "售罄" : "正常"
    },
    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePreview (file) {
      console.log(file);
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return (isJPG || isPNG) && isLt1M;
    },
    cancel () {
      this.dialogFormVisible = false;
    }
  }
}
</script>

<style>
.block {
  height: 100%;
  padding: 40px 0px;
}
.order_title {
  margin: 40px 20px;
}

.el-drawer__body {
  overflow: auto;
}

.el-drawer__container ::-webkit-scrollbar {
  display: none;
}

.edit-button {
  margin-bottom: 10px;
}
</style>>
